home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 2180 < prev    next >
Encoding:
Text File  |  1996-08-05  |  2.1 KB  |  61 lines

  1. Path: io.salford.ac.uk!aber!not-for-mail
  2. From: auj@aber.ac.uk (Alun "Penguin" Jones)
  3. Newsgroups: comp.lang.c
  4. Subject: Re: Examples of using "volatile"?
  5. Date: 19 Jan 1996 14:45:49 -0000
  6. Organization: Prifysgol Cymru (University of Wales) Aberystwyth
  7. Message-ID: <4doaqt$jnd@osfa.aber.ac.uk>
  8. References: <4djoj2$mr1@post.gsfc.nasa.gov>
  9. NNTP-Posting-Host: osfa.aber.ac.uk
  10.  
  11. Further up the screen Stephen.Maher@gsfc.nasa.gov (Stephen Maher) wrote:
  12. >
  13. >I understand the *theory* behind volatile (e.g., to avoid unwanted
  14. >side-effects?).  I also realize it's probably implementation
  15. >dependent. But some examples from any implementation should help me
  16. >understand its use a little better.
  17.  
  18. Here's an example, the like of which happened to me some while back. The
  19. exact example was using a handler to catch a hardware interrupt. But
  20. signal() can give the same effect:
  21.  
  22. #include <signal.h>
  23. int i=1;
  24. void interrupt(int sig)
  25. {
  26.     i = 0;
  27.     return;
  28. }
  29.  
  30. int main(void)
  31. {
  32.     signal(SIGINT, interrupt);
  33.  
  34.     while (i);
  35.     return 0;
  36. }
  37.  
  38. In this case, we loop until i becomes zero, which happens when something
  39. generates SIGINT (^C on Unix should do the job). If i is not volatile,
  40. then the compiler is free to opt to keep i in a register. When the
  41. signal occurs, the handler function will write to the memory copy of i,
  42. but this might not be seen by the main loop if the memory access has
  43. been optimised out.
  44.  
  45. So, depending on your compiler/optimisation level, you've either got an
  46. infinite loop, or you haven't. Specifying i as volatile prevents the
  47. optimisation of the while loop, and therefore guarantees the action of
  48. the program.
  49.  
  50. Dec's compiler on OSF exhibits this behaviour by acting differently for
  51. -O3 from when no optimisation is specified. Acorn's compiler performs
  52. the optimisation by default (and this is where I got bitten).
  53.  
  54. Cheers,
  55. Alun.
  56. -- 
  57. $_='\=*Sxw!jds@j$.jl.dt#Rw%^dcn"K1x(=Bl1nwl!\*1enab^h"F=!J$h%fhcq',
  58. tr&J-ZA-Ij-za-i&A-Za-z&&s&\(&logic&&&s&\*&un&g&s&=&al&g&s&\^&it&g&&
  59. s&%&st&g&&s&\$&ber&g&s&\#&\n&&s&"& of&g,s&([A-Z])& $1&g&&s&\\u&U&&&
  60. s&!&es, &g&s&\\a&A&&s&1&i&g&&print" $_\n";sub liminal{"use perl!";}
  61.